import React, { memo, useCallback, useEffect } from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";

import {
    RankingWrapper
} from "./style";
import { getSizeImage } from "@/utils/format-utils";
import { 
    getPlayListDetailAction,
    changeCurrentIndexAction
} from "@/pages/discover/c-pages/ranking/store/actionCreators";

export default memo(function CJXRankingList() {
    //redux
    const { leftRankingList, currentIndex } = useSelector((state) => {
        return {
            leftRankingList: state.getIn(["ranking", "leftRankingList"]),
            currentIndex: state.getIn(["ranking", "currentIndex"]),
        }
    }, shallowEqual);


    //other hook
    const dispatch = useDispatch();
    useEffect(() => {
        const id = leftRankingList[currentIndex] && leftRankingList[currentIndex].id;
        if (!id) return;
        dispatch(getPlayListDetailAction(id))
    }, [leftRankingList, currentIndex, dispatch])

    const hanldeItemClick = useCallback((index) => {
        // console.log(index);
        dispatch(changeCurrentIndexAction(index))
    }, [dispatch])

    return (
        <RankingWrapper>
            {leftRankingList.map((item, index) => {
                let header;
                if (index === 0 || index === 4) {
                    header = <div className="ranking-title">{index === 0 ? "云音乐特色榜" : "全球媒体榜"}</div>
                }
                return (
                    <div className="content" key={item.id}>
                        { header }
                        <div className={`item ${currentIndex===index?"active":""}`} onClick={e => hanldeItemClick(index)}>
                            <img src={getSizeImage(item.coverImgUrl, 40)} alt="图" />
                            <div className="right">
                                <div className="title line_hide_1">{item.name}</div>
                                <div className="update">{item.updateFrequency}</div>
                            </div>
                        </div>
                    </div>
                )
            })}

        </RankingWrapper>
    )
})